/**
 * @description 柱状图(横、竖)
 *  横、竖。唯一区别是：xAxis,yAxis轴配置对调了
 */

import echarts from "../echart"
import { useEffect, useRef } from 'react';
import useChartResize from "@/hooks/useChartResize";
import { getLineMock } from "../mockData";

function Bar({ configData, chart }) {

  let { title, graphType } = configData

  const chartRef = useRef(null)
  const boxRef = useRef()

  useEffect(() => {

    let themeConfig = chart.bar
    let limitNum = chart.base.barNum

    // 基于准备好的dom，初始化echarts实例
    if (!chartRef.current) {
      let myChart = echarts.init(boxRef.current)
      chartRef.current = myChart
    }


    // [1] 获取随机数据
    let [xAxisData, yAxisData] = getLineMock(limitNum)

    let xAxis, yAxis
    if (graphType == '横') {
      // 横向的
      xAxis = {
        ...themeConfig.xAxis,
        type: 'value'
      }
      yAxis = {
        ...themeConfig.yAxis,
        type: 'category',
        // 限制个数
        data: xAxisData
      }
    } else {
      // 竖
      xAxis = {
        ...themeConfig.xAxis,
        type: 'category',
        data: xAxisData
      }
      yAxis = {
        ...themeConfig.yAxis,
        type: 'value'
      }
    }


    const options = {
      backgroundColor: themeConfig.backgroundColor,
      color: themeConfig.color,
      title: {
        ...themeConfig.title,
        text: title,
      },
      // 图例组件
      legend: themeConfig.legend,
      // 直角坐标系内绘图网格
      grid: themeConfig.grid,
      // 提示框组件
      tooltip: themeConfig.tooltip,
      // x轴
      xAxis,
      // y轴
      yAxis,
      series: [{
        ...themeConfig.series,
        data: yAxisData,
        type: 'bar',
      }]
    }


    // 绘制图表
    chartRef.current.setOption(options, true);


  }, [chart])


  useChartResize(boxRef, chartRef)

  return (
    <div className='chart-box' ref={boxRef} ></div>
  )
}
export default Bar